package com.shuqi.activity;

import java.util.List;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.shuqi.activity.adapter.MoreRecommengAdapter;
import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.MainController;
import com.shuqi.controller.MoreRecommengController;
import com.shuqi.controller.R;
import com.shuqi.database.model.BookInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.bean.MoreRecommendInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 通用更多推荐页面
 * 
 * @author zhuchen
 * 
 */
public class MoreRecommengActivity extends ActivityBase implements IEventListener,
        HttpRequestErrListener, OnClickListener, OnItemClickListener {

    private final int INIT = EventTypeConstants.BASE;
    private final int INITSUCCESS = INIT + 1;
    private final int SHOW404 = INITSUCCESS + 1;
    private final int LOADMORE_ERROR = SHOW404 + 1;

    private MoreRecommengController controller;
    private MoreRecommengAdapter adapter;
    private MoreRecommendInfo moreRecommendInfo;
    private ListView mActMoreRecommengListView;
    private List<BookInfo> mActMoreRecommengListData;
    private int totalCount;
    private int pageIndex = 1;// 请求页
    private LinearLayout line_404;// 无网络
    private LinearLayout layoutLoading;// 进度圈
    private String color;

    /** 加载更多footer */
    private MyListFooter mListFooter;
    private CommonTitle mTitle;
    private ControlHandler handler = new ControlHandler(this) {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case INIT:
                    activityLogicForward();
                    setAllOnListener();
                    break;
                case INITSUCCESS:
                    activityInitData();
                    break;
                case SHOW404:
                    layoutLoading.setVisibility(View.GONE);
                    line_404.setVisibility(View.VISIBLE);
                    // showMsg("网络异常...");
                    break;
                case LOADMORE_ERROR:
                    layoutLoading.setVisibility(View.GONE);
                    mListFooter.loadingError();
                    showMsg("网络异常...");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (controller == null) {
            controller =
                    (MoreRecommengController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_MORERECOMMEND, this);
        }
        controller.addEventListener(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_morerecommeng);
        handler.sendEmptyMessage(INIT);

    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                moreRecommendInfo = (MoreRecommendInfo) data;
                handler.sendEmptyMessage(INITSUCCESS);
                break;
            default:
                if (mActMoreRecommengListData == null) {
                    handler.sendEmptyMessage(SHOW404);
                } else {
                    handler.sendEmptyMessage(LOADMORE_ERROR);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        controller.onDestroy();
        super.onDestroy();
    }

    /**
     * 初始化数据
     */
    @Override
    public void activityLogicForward() {
        layoutLoading = (LinearLayout) findViewById(R.id.include_loading);
        line_404 = (LinearLayout) findViewById(R.id.include_error);

        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        mTitle.setTitle(getIntent().getStringExtra("title"));
        color = getIntent().getStringExtra("color");

        mActMoreRecommengListView = (ListView) findViewById(R.id.act_morerecommeng_list);
    }

    /** 设置监听事件 */
    private void setAllOnListener() {
        findViewById(R.id.retry).setOnClickListener(this);

        MyFooterListener listener = new MyFooterListener() {

            @Override
            public void reload() {
                requestAppList();
                mListFooter.loadingStart();
            }

            @Override
            public void loadNext() {
                requestAppList();
                mListFooter.loadingStart();
            }

            @Override
            public boolean hasNext() {
                if (mActMoreRecommengListData == null || mActMoreRecommengListData.size() == 0) {
                    return false;
                }
                return (mActMoreRecommengListData.size() < totalCount);
            }

        };

        mListFooter = new MyListFooter(this, listener);
        mActMoreRecommengListView.addFooterView(mListFooter);
        mActMoreRecommengListView.setOnItemClickListener(this);

        requestAppList();
        mListFooter.loadingStart();
        layoutLoading.setVisibility(View.VISIBLE);
    }

    @Override
    public void activityInitData() {
        line_404.setVisibility(View.GONE);
        layoutLoading.setVisibility(View.GONE);

        if (moreRecommendInfo != null) {
            try {
                if(!TextUtils.isEmpty(moreRecommendInfo.getTotalCount())){
                    totalCount = Integer.parseInt(moreRecommendInfo.getTotalCount());
                }
            } catch (Exception e) {
                Log4an.i("activityInitData:"+e.toString());
            }
            if (moreRecommendInfo.getBookInfo() != null
                    && moreRecommendInfo.getBookInfo().size() > 0) {
                List<BookInfo> templist = moreRecommendInfo.getBookInfo();
                if (mActMoreRecommengListData == null) {
                    mActMoreRecommengListData = templist;
                } else {
                    mActMoreRecommengListData.addAll(templist);
                }
                if (adapter == null) {
                    adapter = new MoreRecommengAdapter(this, color);
                    adapter.setDataList(mActMoreRecommengListData);
                    mActMoreRecommengListView.setAdapter(adapter);
                } else {
                    adapter.setDataList(mActMoreRecommengListData);
                    adapter.notifyDataSetChanged();
                }
                mListFooter.loadingSuccess();
                pageIndex++;
            }
        }
    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.retry:
//                if (!Util.isNetworkConnected(this)) {
//                    return;
//                } else {
//                    controller.handle(0, getIntent().getStringExtra("columnId"), pageIndex);
//                    layoutLoading.setVisibility(View.VISIBLE);
//                }
                
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {

                    @Override
                    public void netErrorCallback() {
                        controller.handle(0, getIntent().getStringExtra("columnId"), pageIndex);
                        layoutLoading.setVisibility(View.VISIBLE);

                    }
                });
                break;
            default:
                break;
        }

    }


    /** 翻页加载请求 */
    private void requestAppList() {
        controller.handle(0, getIntent().getStringExtra("columnId"), pageIndex); // 获取app数据
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
        if (mActMoreRecommengListData != null && mActMoreRecommengListData.size() > 0) {
            BookInfo bookInfo = mActMoreRecommengListData.get(position);
            // 总状态为开
            if (BookInfo.BOOK_OPEN.equals(bookInfo.getBookHideState())) {
                // 封面页开
                if (BookInfo.OPEN == bookInfo.getCoverHideState()) {
                    BookCoverActivity.openBookCover(this, bookInfo.getBookId());
                } else {
                    // 封面关
                    showMsg(getString(R.string.error_bookswitch_coverisclose));
                    return;
                }
            } else {
                // 总状态位关
                showMsg(getString(R.string.error_bookswitch_ishide));
                return;
            }
        }

    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
